package com.zhouyer.study.logindemo.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Map;

/**
 * 登录控制器
 *
 * @author zhouyao
 * @version 1.0
 * @date 2021/9/19 5:40 下午
 */
@Controller
public class LoginController {
    @GetMapping("/login")
    public String login(Map<String, Object> map, HttpServletRequest request, HttpSession session) {
        map.put("port", request.getLocalPort());
        map.put("sessionId", session.getId());
        map.put("context", request.getContextPath());
        return "login";
    }

    @PostMapping("/doLogin")
    public String loginSystem(String username, String password, HttpSession session) {
        // 合法用户，信息写入session，同时跳转到系统主页面
        if ("admin".equals(username) && "admin".equals(password)) {
            session.setAttribute("username", username + System.currentTimeMillis());
            return "redirect:index";
        } else {
            // 非法用户返回登录页面
            return "redirect:login";
        }
    }
}
